package com.wq.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wq.common.R;
import com.wq.entity.Employee;
import com.wq.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.jni.Local;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @ description
 * @ author wuyunpeng
 * @ create 2022-07-20 14:00
 */
@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;

    /**
     * 登录逻辑：
     * 1）password进行MD5加密
     * 2）根据username唯一查询用户
     * 3）用户不存在返回错误结果
     * 4）用户密码错误返回错误结果
     * 5）用户状态禁用返回错误结果
     * 6）登录成功，将userID存入session保存登录状态，返回正确结果
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public R<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
//        1.password md5 加密
        String password = employee.getPassword();
        password = DigestUtils.md5DigestAsHex(password.getBytes());

//        2.根据username（唯一）查询数据库
        final LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

//        3.如果用户不存在，返回登录失败的结果
        if (emp == null) {
            return R.error("用户名或密码错误");
        }

//        4.如果密码错误，返回登陆失败的结果
        if (!emp.getPassword().equals(password)) {
            return R.error("用户名或密码错误");
        }

//        5.如果员工状态已禁用，返回禁用结果
        if (emp.getStatus() == 0) {
            return R.error("账号已禁用");
        }

//        6.登陆成功，将员工id存入session并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());
        return R.success(emp);
    }

    /**
     * 退出登录逻辑
     * 1）删除session，返回正确结果
     * 2）前端进行页面的跳转
     *
     * @param request
     * @return
     */
    @PostMapping("/logout")
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("employee");
        return R.success("退出成功");
    }

    /**
     * 添加员工逻辑
     * 1）对密码进行加密后重新赋值给employee
     * 2）MyBatisPlus保存
     * 3）通用表达式字段由MyMetaObjectHandler自动填充
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping
    public R<String> save(HttpServletRequest request, @RequestBody Employee employee) {
//        设置统一初始化密码123456
        String password = DigestUtils.md5DigestAsHex("123456".getBytes());
        employee.setPassword(password);
        employeeService.save(employee);
        return R.success("新增员工成功");
    }

    /**
     * 分页逻辑
     * 1）根据page，pageSize构造Page对象
     * 2）name不为空，构造LambdaQueryWrapper对象模糊查询
     * 3）MyBatisPlus分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, String name) {
        Page pageInfo = new Page(page, pageSize);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        lqw.like(!StringUtils.isEmpty(name), Employee::getName, name);
        lqw.orderByDesc(Employee::getUpdateTime);
        employeeService.page(pageInfo, lqw);
        return R.success(pageInfo);
    }

    /**
     * 通用的员工修改
     *
     * @param request
     * @param employee
     * @return
     */
    @PutMapping
    public R<String> update(HttpServletRequest request, @RequestBody Employee employee) {
        employee.setUpdateTime(LocalDateTime.now());
        Long empID = (Long) request.getSession().getAttribute("employee");
        employee.setUpdateUser(empID);
        LambdaQueryWrapper<Employee> lqw = new LambdaQueryWrapper<>();
        employeeService.updateById(employee);
        return R.success("员工状态修改成功!");
    }

    /**
     * GET 请求有两种接收格式
     * restful 风格 ==> 参数以 / 写在路径中
     * ? & 衔接参数
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<Employee> modify(@PathVariable(value = "id") Long id) {
        final Employee employee = employeeService.getById(id);
        return R.success(employee);
    }
}
